//获取url中的get参数
function getQuery(key) {
    // 获取所有参数
    var query = window.location.search.substring(1);
    var hash = window.location.hash.substring(1);
    // 如果锚点后面有参数，把锚点后面的参数加入到search参数中
    if(hash.indexOf("?") > -1){
        query += "&" + hash.split("?")[1];
    }
    var key_values = query.split("&");
    var params = {};
    // 遍历参数并存入params对象
    key_values.map(function (key_val){
        var key_val_arr = key_val.split("=");
        params[key_val_arr[0]] = key_val_arr[1];
    });
    // 如果找到了key对应的参数，返回对应值
    if(typeof params[key]!="undefined"){
        return params[key];
    }
    // 如果没找到，返回空字符串
    return "";
}
//获取域名部分
function getDomainFromUrl(url) {
    if(!url||url==""){
        url=window.location.href;
    }
    const regex = /^https?:\/\/([^\/]+)/i;
    const match = url.match(regex);
    return match[1];
}
//获取协议部分
function getProtocolFromUrl(url) {
    if(!url||url==""){
        url=window.location.href;
    }
    const regex = /^(https?)/i;
    const match = url.match(regex);
    return match[1];
} 
//js获取当前时间
function getNowDate() {
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    if(mon<10){
        mon="0"+mon;
    }
    var date = myDate.getDate(); //获取当前日
    if(date<10){
        date="0"+date;
    }
    var hours = myDate.getHours(); //获取当前小时
    if(hours<10){
        hours="0"+hours;
    }
    var minutes = myDate.getMinutes(); //获取当前分钟
    if(minutes<10){
        minutes="0"+minutes;
    }
    var seconds = myDate.getSeconds(); //获取当前秒
    if(seconds<10){
        seconds="0"+seconds;
    }
    var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
    return now;
}
//js实现类似php trim函数
function trim(str, char) {
    if (char) {
        str=str.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
    }
    return str.replace(/^\s+|\s+$/g, '');
};
//延迟展示
function displayGreetings(greetings,callback) {
	if(!greetings||greetings.length==0){
		return;
	}
	let delay=0;
	for (let i = 0; i < greetings.length; i++) {
		if(!greetings[i].delay_second){
			delay+=3;
		}else{
			delay+=greetings[i].delay_second;
		}
		greetings[i].delay_second=delay;
	}
	for (let i = 0; i < greetings.length; i++) {
		let greeting = greetings[i];
		setTimeout(function() {
		  // 在这里执行你想展示的操作，例如：
		  callback(greeting);
		}, greeting.delay_second*1000);
	}
}
//缩短时间
function shortTime(t){
    let time=new Date(t);
    let today = new Date();
    let todayYear = today.getFullYear();
    let todayMonth = today.getMonth()+1;
    let todayDate = today.getDate();

    let targetYear = time.getFullYear();
    let targetMonth = time.getMonth()+1;
    let targetDate = time.getDate();
    let targetHour = time.getHours();
    let targetMinutes = time.getMinutes();
    let targetSeconds = time.getSeconds();
    // 同一天，只显示小时、分钟、秒
    if (todayYear === targetYear && todayMonth === targetMonth && todayDate === targetDate) {
        if (targetHour < 10) {
            targetHour = "0" + targetHour;
        }
        if (targetMinutes < 10) {
            targetMinutes = "0" + targetMinutes;
        }
        if (targetSeconds < 10) {
            targetSeconds = "0" + targetSeconds;
        }
        return targetHour + ":" + targetMinutes + ":" + targetSeconds;
    }
    // 同一年，只显示月日等
    if (todayYear === targetYear) {

        if (targetMonth < 10) {
            targetMonth = "0" + targetMonth;
        }
        if (targetDate < 10) {
            targetDate = "0" + targetDate;
        }
        if (targetHour < 10) {
            targetHour = "0" + targetHour;
        }
        if (targetMinutes < 10) {
            targetMinutes = "0" + targetMinutes;
        }
        if (targetSeconds < 10) {
            targetSeconds = "0" + targetSeconds;
        }
        return `${targetMonth}-${targetDate} `+targetHour + ":" + targetMinutes + ":" + targetSeconds;
    }
    return t;
}

// Base64加密
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}
function urlDecode(str) {
  return decodeURIComponent(str.replace(/\%20/g, '+'));
}
// Base64解密
function b64DecodeUnicode(str) {
	str=urlDecode(str);
  return decodeURIComponent(atob(str.replace(/\_/g, '/').replace(/\-/g, '+'))
    .split('')
    .map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    })
    .join(''));
}

//转换产品卡片
function replaceProduct(str){
    return str.replace(/product\[([^\[\]]+?)\]/g, function (product) {
		console.log(str,arguments);
        if(!arguments[1]){
            return;
        }
        let jsonStr=arguments[1].replace(/\'/g,'"');
        try{
            let info=JSON.parse(jsonStr);
            if(typeof info=="undefined"){
                return;
            }
            if(!info.title) info.title="智能客服系统产品卡片";
			if(!info.price) info.price="￥0";
			if(info.img){
			    info.img="<img src='"+info.img+"'/>";
			}else{
				info.img="";
			}
            if(!info.url) info.url="/";
            let html= `
                    <a class="elfCard" href="`+info.url+`" target="_blank"/>
                    `+info.img+`

                    <div class="elfCardTitle">
                        <p class="elfCardTitle">`+info.title+`</p>
                        <p class="elfCardPrice">`+info.price+`</p>
                    </div>
                    </a>
            `;
            return html;
        }catch (e) {
            return jsonStr;
        }
    });
}
//播放声音
function alertSound(id,src){
    var b = document.getElementById(id);
    if(src){
        b.src=src;
    }
    var p = b.play();
    p && p.then(function(){}).catch(function(e){
		console.log(e,b.src);
	});
}
//浏览器桌面通知
function notify(title, options, callback) {

    // 先检查浏览器是否支持
    if (!window.Notification) {
        console.log("浏览器不支持notify");
        return;
    }
    //options.body=replaceHtml(options.body);
    console.log("浏览器notify权限:", Notification.permission);
    // 检查用户曾经是否同意接受通知
    if (Notification.permission === 'granted') {
        var notification = new Notification(title, options); // 显示通知
        if (notification && callback) {
            notification.onclick = function(event) {
                callback(notification, event);
            }
            setTimeout(function () {
                notification.close();
            },3000);
        }
    } else {
        Notification.requestPermission().then( (permission) =>function(){
            console.log("请求浏览器notify权限:", permission);
            if (permission === 'granted') {
                notification = new Notification(title, options); // 显示通知
                if (notification && callback) {
                    notification.onclick = function (event) {
                        callback(notification, event);
                    }
                    setTimeout(function () {
                        notification.close();
                    }, 3000);
                }
            } else if (permission === 'default') {
                console.log('用户关闭授权 可以再次请求授权');
            } else {
                console.log('用户拒绝授权 不能显示通知');
            }
        });
    }

}
//标题闪动
var flashing = false;

function flashTitle() {
    if (flashing) {
        return;
    }

    flashing = true;

    var originalTitle = document.title;
    var intervalId;
    var newTitle = "🔥✉️" + originalTitle;

    function changeTitle() {
        document.title = document.title == originalTitle ? newTitle : originalTitle;
    }

    intervalId = setInterval(changeTitle, 1000);

    window.onfocus = function () {
        clearInterval(intervalId);
        document.title = originalTitle;
        flashing = false;
    };
}
//兼容的getUserMedia
function getCompatibleUserMedia(constraints, successCallback, errorCallback) {
  var media = (navigator.getUserMedia || navigator.webkitGetUserMedia ||navigator.mozGetUserMedia ||navigator.msGetUserMedia);
  
  if (media) {
    media.call(navigator, constraints, successCallback, errorCallback);
	return true;
  } else {
    console.error("Your browser does not support the getUserMedia API.");
	return false;
  }
}
//获取图片链接
function getImageUrl(imgUrl,host){
	var prefix=imgUrl.substr(0,4);
	if(prefix=='http'){
		return imgUrl;
	}else{
		return host+imgUrl;
	}
}
function replaceContent (content,baseUrl) {// 转义聊天内容中的特殊字符
    if(typeof baseUrl=="undefined"){
        baseUrl="";
    }
    content=replaceSpecialTag(content,baseUrl);
    return content;
}
function replaceSpecialTag(str,baseUrl) {
    if(typeof baseUrl=="undefined"){
        baseUrl="";
    }
    str=replaceImage(str,baseUrl);
    str=replaceAudio(str,baseUrl)
    str=replaceFile(str)
    str=replaceMutiFile(str,baseUrl)
    str=replaceProduct(str);
    return str;
}
function replaceImage(str,baseUrl){
    return str.replace(/img\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
        var src = face.replace(/^img\[/g, '').replace(/\]/g, '');;
		src=getImageUrl(src,baseUrl);
        return '<img data-src="'+baseUrl+ src +'" class="chatImagePic"  src="' +src + '?width=400" />';
    })
}
function replaceAudio(str,baseUrl){
    return str.replace(/audio\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
        var src = face.replace(/^audio\[/g, '').replace(/\]/g, '');;
        //return '<div class="chatAudio"><audio controls ref="audio" src="'+src+'" class="audio"></audio></div>';
        var html= `
              <audio controls ref="audio" src="`+baseUrl+src+`" class="audio" style="height: 38px;"></audio>
            `;

        return html;
    })
}
function replaceFile(str){
    return str.replace(/file\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
        var src = face.replace(/^file\[/g, '').replace(/\]/g, '');;
        return '<a href="'+src+'" target="_blank"/><i style="font-size: 26px;color: #606266" class="el-icon-folder-checked"></i></a>';
    })
}
function replaceMutiFile(str,baseUrl){
    return str.replace(/mutiFile\[(.*?)\]/g, function (result) {
        var mutiFiles=result.match(/mutiFile\[(.*?)\]/)
        if (mutiFiles.length<2){
            return result;
        }
        //return result;

        var info=JSON.parse(mutiFiles[1])
        var imgSrc="";
        switch(info.ext){
            case ".mp3":
                imgSrc="/static/images/ext/MP3.png";
                break;
            case ".zip":
                imgSrc="/static/images/ext/ZIP.png";
                break;
            case ".txt":
                imgSrc="/static/images/ext/TXT.png";
                break;
            case ".7z":
                imgSrc="/static/images/ext/7z.png";
                break;
            case ".bpm":
                imgSrc="/static/images/ext/BMP.png";
                break;
            case ".png":
                imgSrc="/static/images/ext/PNG.png";
                break;
            case ".jpg":
                imgSrc="/static/images/ext/JPG.png";
                break;
            case ".jpeg":
                imgSrc="/static/images/ext/JPEG.png";
                break;
            case ".pdf":
                imgSrc="/static/images/ext/PDF.png";
                break;
            case ".doc":
                imgSrc="/static/images/ext/DOC.png";
                break;
            case ".docx":
                imgSrc="/static/images/ext/DOCX.png";
                break;
            case ".rar":
                imgSrc="/static/images/ext/RAR.png";
                break;
            case ".xlsx":
                imgSrc="/static/images/ext/XLSX.png";
                break;
            case ".csv":
                imgSrc="/static/images/ext/XLSX.png";
                break;
            default:
                imgSrc="/static/images/ext/default.png";
                break;
        }
        var html= `<div onclick="window.open('`+baseUrl+info.path+`')" class="elfCard">
                        <div><img src='`+baseUrl+imgSrc+`' style='width: 38px;height: 38px;' /></div>
                        <div class="elfCardTitle">
                            <div class="elfCardTitle">`+info.name+`</div>
                            <div style="font-size: 12px;color: #666">`+formatFileSize(info.size)+`</div>
                        </div>
                    </div>`;
        return html;
    })
}
function formatFileSize(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024*1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024*1024*1024)) {
        var temp = fileSize / (1024*1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024*1024*1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}
export default {
	b64EncodeUnicode,b64DecodeUnicode,replaceSpecialTag,alertSound,notify,flashTitle,getCompatibleUserMedia,
	getQuery,getDomainFromUrl,getProtocolFromUrl,getNowDate,trim,displayGreetings,shortTime,getImageUrl,
	replaceContent
}